/**
 * 增强的收件人管理组件
 */
import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Tag,
  Popconfirm,
  Modal,
  Form,
  Select,
  Alert,
  Tooltip,
  Divider,
  Upload,
  message,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  ImportOutlined,
  DatabaseOutlined,
  UserOutlined,
  MailOutlined,
  EditOutlined,
  UploadOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { UploadProps } from 'antd';
import RecipientSelector from '../RecipientSelector';

const { Option } = Select;

interface RecipientData {
  email: string;
  name?: string;
  variables?: Record<string, any>;
}

interface EnhancedRecipientManagerProps {
  value?: RecipientData[];
  onChange?: (recipients: RecipientData[]) => void;
  dataSourceId?: number;
  sendMode?: 'batch' | 'personalized';
  onSendModeChange?: (mode: 'batch' | 'personalized') => void;
}

const EnhancedRecipientManager: React.FC<EnhancedRecipientManagerProps> = ({
  value = [],
  onChange,
  dataSourceId,
  sendMode = 'batch',
  onSendModeChange,
}) => {
  const [recipients, setRecipients] = useState<RecipientData[]>(value);
  const [selectorVisible, setSelectorVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [selectedRecipient, setSelectedRecipient] = useState<RecipientData | null>(null);
  const [editIndex, setEditIndex] = useState<number>(-1);
  const [form] = Form.useForm();

  // 更新收件人列表
  const updateRecipients = (newRecipients: RecipientData[]) => {
    setRecipients(newRecipients);
    onChange?.(newRecipients);
  };

  // 添加单个收件人
  const handleAddRecipient = () => {
    setSelectedRecipient({ email: '', name: '', variables: {} });
    setEditIndex(-1);
    form.resetFields();
    setEditModalVisible(true);
  };

  // 编辑收件人
  const handleEditRecipient = (recipient: RecipientData, index: number) => {
    setSelectedRecipient(recipient);
    setEditIndex(index);
    form.setFieldsValue({
      email: recipient.email,
      name: recipient.name,
    });
    setEditModalVisible(true);
  };

  // 保存收件人编辑
  const handleSaveRecipient = async () => {
    try {
      const values = await form.validateFields();
      const newRecipient: RecipientData = {
        email: values.email,
        name: values.name,
        variables: selectedRecipient?.variables || {},
      };

      let newRecipients: RecipientData[];
      if (editIndex >= 0) {
        // 编辑现有收件人
        newRecipients = [...recipients];
        newRecipients[editIndex] = newRecipient;
      } else {
        // 添加新收件人
        newRecipients = [...recipients, newRecipient];
      }

      updateRecipients(newRecipients);
      setEditModalVisible(false);
      message.success(editIndex >= 0 ? '收件人更新成功' : '收件人添加成功');
    } catch (error) {
      console.error('保存收件人失败:', error);
    }
  };

  // 删除收件人
  const handleDeleteRecipient = (index: number) => {
    const newRecipients = recipients.filter((_, i) => i !== index);
    updateRecipients(newRecipients);
    message.success('收件人删除成功');
  };

  // 批量删除收件人
  const handleBatchDelete = () => {
    updateRecipients([]);
    message.success('已清空所有收件人');
  };

  // 从数据源选择收件人
  const handleSelectFromDataSource = (selectedRecipients: RecipientData[]) => {
    updateRecipients([...recipients, ...selectedRecipients]);
    message.success(`成功添加 ${selectedRecipients.length} 个收件人`);
  };

  // CSV文件上传
  const uploadProps: UploadProps = {
    name: 'file',
    accept: '.csv,.txt',
    beforeUpload: (file) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const text = e.target?.result as string;
          const lines = text.split('\n').filter(line => line.trim());
          const newRecipients: RecipientData[] = [];

          lines.forEach((line, index) => {
            const parts = line.split(',').map(part => part.trim());
            if (parts.length >= 1 && parts[0].includes('@')) {
              newRecipients.push({
                email: parts[0],
                name: parts[1] || `用户${index + 1}`,
                variables: {},
              });
            }
          });

          if (newRecipients.length > 0) {
            updateRecipients([...recipients, ...newRecipients]);
            message.success(`成功导入 ${newRecipients.length} 个收件人`);
          } else {
            message.warning('文件中没有找到有效的邮箱地址');
          }
        } catch (error) {
          message.error('文件解析失败');
        }
      };
      reader.readAsText(file);
      return false; // 阻止自动上传
    },
  };

  // 导出收件人列表
  const handleExportRecipients = () => {
    if (recipients.length === 0) {
      message.warning('没有收件人可以导出');
      return;
    }

    const csvContent = recipients.map(r => `${r.email},${r.name || ''}`).join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', 'recipients.csv');
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success('收件人列表导出成功');
  };

  // 收件人表格列定义
  const columns: ColumnsType<RecipientData> = [
    {
      title: '邮箱地址',
      dataIndex: 'email',
      key: 'email',
      render: (text: string) => (
        <Space>
          <MailOutlined />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => text || '-',
    },
    {
      title: '变量数量',
      key: 'variables',
      render: (_, record: RecipientData) => {
        const variableCount = record.variables ? Object.keys(record.variables).length : 0;
        return (
          <Tag color={variableCount > 0 ? 'blue' : 'default'}>
            {variableCount} 个变量
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: RecipientData, index: number) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button
              type="text"
              icon={<EditOutlined />}
              onClick={() => handleEditRecipient(record, index)}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个收件人吗？"
            onConfirm={() => handleDeleteRecipient(index)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="text" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card title="收件人管理" size="small">
        {/* 发送模式选择 */}
        <div style={{ marginBottom: 16 }}>
          <Alert
            message="发送模式"
            description={
              <div>
                <Select
                  value={sendMode}
                  onChange={onSendModeChange}
                  style={{ width: 200 }}
                >
                  <Option value="batch">批量发送（相同内容）</Option>
                  <Option value="personalized">个性化发送（不同内容）</Option>
                </Select>
                <div style={{ marginTop: 8, fontSize: 12, color: '#666' }}>
                  {sendMode === 'batch' 
                    ? '所有收件人将收到相同的邮件内容' 
                    : '每个收件人将根据其数据收到个性化的邮件内容'
                  }
                </div>
              </div>
            }
            type="info"
            showIcon
          />
        </div>

        {/* 操作按钮 */}
        <div style={{ marginBottom: 16 }}>
          <Space wrap>
            <Button
              type="primary"
              icon={<DatabaseOutlined />}
              onClick={() => setSelectorVisible(true)}
              disabled={!dataSourceId}
            >
              从数据源选择
            </Button>
            <Button
              icon={<PlusOutlined />}
              onClick={handleAddRecipient}
            >
              手动添加
            </Button>
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>
                导入CSV文件
              </Button>
            </Upload>
            <Button
              icon={<DownloadOutlined />}
              onClick={handleExportRecipients}
              disabled={recipients.length === 0}
            >
              导出列表
            </Button>
            {recipients.length > 0 && (
              <Popconfirm
                title="确定要清空所有收件人吗？"
                onConfirm={handleBatchDelete}
                okText="确定"
                cancelText="取消"
              >
                <Button danger>
                  清空列表
                </Button>
              </Popconfirm>
            )}
          </Space>
        </div>

        {!dataSourceId && (
          <Alert
            message="提示"
            description="请先选择数据源，然后可以从数据源中选择收件人"
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}

        {/* 收件人统计 */}
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Tag color="blue">总计: {recipients.length} 人</Tag>
            <Tag color="green">
              有姓名: {recipients.filter(r => r.name).length} 人
            </Tag>
            <Tag color="orange">
              有变量: {recipients.filter(r => r.variables && Object.keys(r.variables).length > 0).length} 人
            </Tag>
          </Space>
        </div>

        {/* 收件人表格 */}
        <Table
          columns={columns}
          dataSource={recipients}
          rowKey={(record, index) => `${record.email}-${index}`}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 个收件人`,
          }}
          locale={{ emptyText: '暂无收件人，请添加收件人' }}
          size="small"
        />
      </Card>

      {/* 收件人选择器 */}
      <RecipientSelector
        visible={selectorVisible}
        onClose={() => setSelectorVisible(false)}
        onConfirm={handleSelectFromDataSource}
        currentDataSourceId={dataSourceId}
      />

      {/* 编辑收件人弹窗 */}
      <Modal
        title={editIndex >= 0 ? '编辑收件人' : '添加收件人'}
        open={editModalVisible}
        onOk={handleSaveRecipient}
        onCancel={() => setEditModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="email"
            label="邮箱地址"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' },
            ]}
          >
            <Input placeholder="请输入邮箱地址" />
          </Form.Item>

          <Form.Item name="name" label="姓名">
            <Input placeholder="请输入姓名（可选）" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default EnhancedRecipientManager;
